package cn.iocoder.yudao.module.system.controller.admin.mini.orderInfo.back.service.back;

import cn.hutool.json.JSONObject;
import cn.hutool.json.XML;
import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.module.system.controller.admin.mini.orderInfo.back.controller.admin.back.WxLoginVo;
import cn.iocoder.yudao.module.system.controller.admin.mini.orderInfo.back.controller.admin.back.vo.BackPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.mini.orderInfo.back.dal.dataobject.back.BackDO;
import cn.iocoder.yudao.module.system.controller.admin.mini.orderInfo.back.dal.mysql.back.BackMapper;
import cn.iocoder.yudao.module.system.controller.admin.mini.orderInfo.back.util.RefundOrder;
import cn.iocoder.yudao.module.system.controller.admin.mini.orderInfo.order.dal.dataobject.order.OrderDO;
import cn.iocoder.yudao.module.system.controller.admin.mini.orderInfo.order.dal.mysql.order.OrderMapper;
import com.github.wxpay.sdk.WXPayUtil;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.net.ssl.SSLContext;

import org.springframework.validation.annotation.Validated;

import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;
import java.security.KeyStore;
import java.text.SimpleDateFormat;
import java.util.*;
import cn.iocoder.yudao.framework.common.pojo.PageResult;



/**
 * 退/换货 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class BackServiceImpl implements BackService {

    @Resource
    BackMapper backMapper;
    @Resource
    OrderMapper orderMapper;

    public WxLoginVo wxLoginVo = new WxLoginVo();

    @Override
    public BackDO getBack(Integer id) {
        return backMapper.selectById(id);
    }

    @Override
    public PageResult<BackDO> getBackPage(BackPageReqVO pageReqVO) {
        return backMapper.selectPage(pageReqVO);
    }

    @Override
    public void refund(Integer id) throws Exception {
        BackDO backDO = backMapper.selectById(id);
        if (backDO==null)
            throw new ServiceException(500,"退货单不存在,请刷新");
        OrderDO orderDO = orderMapper.selectById(backDO.getOrderId());
        if (orderDO==null)
            throw new ServiceException(500,"订单不存在");

        backDO.setPayStatus(2);
        //退款
//        if (refound(dataMap))
        new RefundOrder().refundOrder(orderDO.getPaypalCode(),backDO.getPrice(),orderDO.getId().toString());
        backDO.setPayStatus(1);
        backMapper.updateById(backDO);
    }


    public  boolean refound(Map<String, String> dataMap) {
        boolean flog=false;
        try {
            //将传来的map转xml
            StringBuilder sb = new StringBuilder();
            sb.append("<xml>");
            for (String key : dataMap.keySet()) {
                String value = "<![CDATA[" + dataMap.get(key) + "]]>";
                sb.append("<").append(key).append(">").append(value).append("</").append(key).append(">");
                System.out.println();
            }
            sb.append("</xml>");
            String xmlString = sb.toString();
            return doRefoud(xmlString);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flog;
    }
    private boolean doRefoud(String xmlString) throws Exception {
        //是否退款成功
        boolean flog=false;

        //证书 是从微信商户平台-》账户设置-》 API安全 中下载的
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        //我想的是把证书传到服务器上，没写出来
        try (InputStream inputStream = Files.newInputStream(new File(wxLoginVo.keyPath).toPath())) {
            //这里写密码，默认是MCHID
            keyStore.load(inputStream, wxLoginVo.mchId.toCharArray());
        }
        SSLContext sslContext = SSLContexts.custom().loadKeyMaterial(keyStore, wxLoginVo.mchId.toCharArray()).build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.getDefaultHostnameVerifier());

        try (CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build()) {
            //请求路径
            HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/secapi/pay/refund");
            StringEntity stringEntity = new StringEntity(xmlString, "UTF-8");
            httpPost.setEntity(stringEntity);
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                HttpEntity entity = response.getEntity();
                //接受到返回信息
                String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.err.println(jsonStr);
                if (check(jsonStr))
                    flog=true;

                EntityUtils.consume(entity);
            }
        }

        return flog;
    }

    //xml相应判断
    public boolean check(String xml){
        boolean flog=false;
        try {
            net.sf.json.JSONObject json = net.sf.json.JSONObject.fromObject(XML.toJSONObject(xml).get("xml").toString());
            String code = json.getString("result_code");
            if (code.equals("SUCCESS"))
                flog=true;
        }catch (Exception e){
        }
        return flog;
    }

    public static void main(String[] args) {
        JSONObject entries = XML.toJSONObject("<xml><return_code><![CDATA[SUCCESS]]></return_code>\n" +
                "<return_msg><![CDATA[OK]]></return_msg>\n" +
                "<appid><![CDATA[wx13987d641abc9d0e]]></appid>\n" +
                "<mch_id><![CDATA[1645826330]]></mch_id>\n" +
                "<nonce_str><![CDATA[UI6qkHednpNPKyQE]]></nonce_str>\n" +
                "<sign><![CDATA[3E78C78A17C726840976021DAFA3278A]]></sign>\n" +
                "<result_code><![CDATA[SUCCESS]]></result_code>\n" +
                "<transaction_id><![CDATA[4200001855202306148561396675]]></transaction_id>\n" +
                "<out_trade_no><![CDATA[QW20230614233810]]></out_trade_no>\n" +
                "<out_refund_no><![CDATA[NO20230614233913]]></out_refund_no>\n" +
                "<refund_id><![CDATA[50301906272023061487919828715]]></refund_id>\n" +
                "<refund_channel><![CDATA[]]></refund_channel>\n" +
                "<refund_fee>1</refund_fee>\n" +
                "<coupon_refund_fee>0</coupon_refund_fee>\n" +
                "<total_fee>1</total_fee>\n" +
                "<cash_fee>1</cash_fee>\n" +
                "<coupon_refund_count>0</coupon_refund_count>\n" +
                "<cash_refund_fee>1</cash_refund_fee>\n" +
                "</xml>");
        String xml = entries.get("xml").toString();
        net.sf.json.JSONObject json = net.sf.json.JSONObject.fromObject(xml);
        String code = json.getString("return_code");
//         -> SUCCESS
        System.err.println(code);
    }

}
